/**
 * @Author: Hhx06
 * @Email: huangshm@yoozoo.com
 * @Description:
 * @File:  req
 * @Version: 1.0.0
 * @Date: 2022/06/10 16:57
 */

package message

import (
	"encoding/json"
	"github.com/eyotang/boomer"
	log "github.com/leesper/holmes"
	"github.com/pkg/errors"
	"github.com/valyala/fasthttp"
	"httpTemplate/client"
	"httpTemplate/model"
)

func DealReq(ctx boomer.Context, c *client.Client, url string) bool {
	if err := errors.WithStack(c.NewRequest(ctx, client.ParseURI(url), dealResp).GET().URL(url).Do().Error); err != nil {
		err = errors.Errorf("Request [%s] failed, err: %+v", client.ParseURI(url), err)
		return false
	}
	return true

}

func dealResp(ctx boomer.Context, statusCode int, body []byte) (err error) {
	if statusCode != fasthttp.StatusOK {
		err = errors.Errorf("%s %s", statusCode, fasthttp.StatusMessage(statusCode))
		log.Errorf("HTTP Status Code: %s %s", statusCode, fasthttp.StatusMessage(statusCode))
		return
	}
	if len(body) == 0 {
		err = errors.Errorf("not response data")
		log.Errorf("not response data")
		return
	}

	var resp model.Resp
	if err = json.Unmarshal(body, &resp); err != nil {
		err = errors.Errorf(" json parse err, data is %s,err is %v", string(body), err)
		log.Errorf(" json parse err, data is %s,err is %v", string(body), err)
		return
	}

	if resp.Code == "1" {
		return
	}
	err = errors.Errorf("resp data err, status is %s, desc is %s", resp.Code, resp.Msg)
	log.Errorf("resp data err, status is %s, desc is %s", resp.Code, resp.Msg)
	return
}
